<?php

namespace addons\shopro\controller\user;

use addons\shopro\service\order\OrderCreate;
use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\user\WalletLog;
use app\common\library\Ems;
use app\common\library\Sms;
use addons\shopro\controller\Common;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\order\Aftersale as AftersaleModel;
use app\admin\model\shopro\ThirdOauth;
use app\common\model\shopro\CarQueue;
use app\common\model\shopro\Shop;
use app\common\model\shopro\ShopRestockModel;
use app\common\model\shopro\ShoproPerformanceModel;
use app\common\model\shopro\UserReadModel;
use app\common\model\Userchildren;
use fast\Random;
use think\Db;
use think\exception\PDOException;
use think\Validate;

class User extends Common
{

    protected $noNeedLogin = ['smsRegister', 'accountLogin', 'smsLogin', 'resetPassword', 'register','nation','register1'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        \think\Lang::load(APP_PATH.'api/lang/zh-cn/user.php');        // 加载语言包
    }

    /**
     * 用户数据
     */
    public function data()
    {
        $user = auth_user();
        // 查询用户优惠券数量
        $data['coupons_num'] = UserCouponModel::geted()->where('user_id', $user->id)->count();

        // 订单数量
        $orderNum              = [];
        $orderNum['unpaid']    = OrderModel::where('user_id', $user->id)->unpaid()->count();
        $orderNum['nosend']    = OrderModel::where('user_id', $user->id)->pretendPaid()->nosend()->count();
        $orderNum['noget']     = OrderModel::where('user_id', $user->id)->pretendPaid()->noget()->count();
        $orderNum['nocomment'] = OrderModel::where('user_id', $user->id)->paid()->nocomment()->count();
        $orderNum['aftersale'] = AftersaleModel::where('user_id', $user->id)->needOper()->count();

        $data['order_num'] = $orderNum;

        $this->success('用户数据', $data);
    }

    /**
     * 第三方授权信息
     */
    public function thirdOauth()
    {
        $user = auth_user();

        $provider = $this->request->param('provider', '');
        $platform = $this->request->param('platform', '');
        if (!in_array($platform, ['miniProgram', 'officialAccount', 'openPlatform'])) {
            $this->error(__('Invalid parameters'));
        }
        $where = [
            'platform' => $platform,
            'user_id'  => $user->id
        ];
        if ($provider !== '') {
            $where['provider'] = $provider;
        }
        $oauth = ThirdOauth::where($where)->field('nickname, avatar, platform, provider')->find();
        $this->success('', $oauth);
    }


    /**
     * 用户信息
     */
    public function profile()
    {
        //TODO @ldh: 1.账号被禁用 2.连表查group
        $user = auth_user(true);

        $user = UserModel::with(['parent_user', 'acceleration'])->where('id', $user->id)->find();

        $user->hidden([
            'password',
            'salt',
            'createtime',
            'updatetime',
            'deletetime',
            'remember_token',
            'login_fail',
            'login_ip',
            'login_time',
            'user_json'
        ]);
        $shopInfo      = Shop::where(['user_id' => $this->auth->id, 'status' => 1])->find();
        $user->is_shop = 0;
        if ($shopInfo) {
            $user->is_shop = 1;
        }
        $walletLogModel  = new WalletLog();
        $shifang         = $walletLogModel->where([
            'user_id' => $this->auth->id,
            'type'    => 'score'
        ])->whereIn('event', 'release,release_jixiao,huzhu,zhi_release,cengji_release')->sum('amount');
        if(!$shifang){
            $user->shifang   = '0.00';
        }else{
            $user->shifang   = abs($shifang);
        }
        $user->shifang   += $user->bu_score;
        $user->shifang   = bcadd($user->shifang, $user->score_gift,2);
        $user->all_score = bcadd($user->shifang, $user->score,2);
        $this->success('个人详情', $user);
    }

    /**
     * 更新用户资料
     */
    public function update()
    {
        $user = auth_user();

        $params = $this->request->only(['avatar', 'nickname', 'gender']);
        $this->svalidate($params);

        $user->save($params);
        $user->hidden([
            'password',
            'salt',
            'createtime',
            'updatetime',
            'deletetime',
            'remember_token',
            'login_fail',
            'login_ip',
            'login_time'
        ]);

        $this->success('更新成功', $user);
    }

    /**
     * 账号密码登录
     */
    public function accountLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['account', 'password']);
        $this->svalidate($params, '.accountLogin');

        $ret = $this->auth->login($params['account'], $params['password']);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '注册失败');
        }
    }


    /**
     * 短信验证码登陆
     */
    public function smsLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.smsLogin');
        if (!Sms::check($params['mobile'], $params['code'], 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = UserModel::getByMobile($params['mobile']);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $this->error('该手机号暂未注册');
        }
        if (isset($ret) && $ret) {
            Sms::flush($params['mobile'], 'mobilelogin');
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '登录失败');
        }
    }

    /**
     * @menu 用户注册
     * ''
     * @Date:2024-04-13 15:25
     */
    public function register()
    {
        $username    = $this->request->post('username');
        $password    = $this->request->post('password');
        $passwordtwo = $this->request->post('passwordtwo');
//        $email       = $this->request->post('email');
        $mobile      = $this->request->post('mobile');
        $invite_code = $this->request->post('invite_code');
//        $code        = $this->request->post('code');
        $area        = $this->request->post('area','A');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
//        if(!$code){
//            $this->error('请填写邮箱验证码');
//        }
        if ($password != $passwordtwo) {
            $this->error(__('两次密码不一致'));
        }
//        if (!Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        if(!Ems::check($email,$code,'register')){
//            $this->error('邮箱验证码错误');
//        }
        $extend['invite_code'] = Random::alnum(8);
        if($invite_code){
            $userModel = new \app\common\model\User();
            $UserInfo = $userModel->where(['invite_code' => $invite_code])->find();
            if (!$UserInfo) {
                $this->error(__('邀请人不存在'));
            }
            $extend['parent_user_id'] = $UserInfo['id'];
            $userModel = new \app\common\model\User();
            $extend['area'] = $area;
            $parent_user_id = (string)$UserInfo['id'];
            $extend['area'] = $area;
            $count = $userModel->where(['parent_user_id'=>$UserInfo['id']])->count();
            if(!$count){
                $area = "A";
                $extend['area'] = $area;
            }
            $parent_area_json = digui($parent_user_id, $area);
            $extend['parent_area_json'] = $parent_area_json;
        }
        $ret = $this->auth->register($username, $password, '', $mobile, $extend);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @menu 用户注册
     * ''
     * @Date:2024-04-13 15:25
     */
    public function register1()
    {
        $username    = $this->request->post('username');
        $password    = $this->request->post('password');
        $passwordtwo = $this->request->post('passwordtwo');
//        $email       = $this->request->post('email');
        $mobile      = $this->request->post('mobile');
        $invite_code = $this->request->post('invite_code');
//        $code        = $this->request->post('code');
        $area        = $this->request->post('area');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
//        if(!$code){
//            $this->error('请填写邮箱验证码');
//        }
        if ($password != $passwordtwo) {
            $this->error(__('两次密码不一致'));
        }
//        if (!Validate::is($email, "email")) {
//            $this->error(__('Email is incorrect'));
//        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
//        if(!Ems::check($email,$code,'register')){
//            $this->error('邮箱验证码错误');
//        }
        $extend['invite_code'] = Random::alnum(8);
        if($invite_code){
            $userModel = new \app\common\model\UserCopyModel();
            $UserInfo = $userModel->whereNotIn('id','2095,2096,2098,2099')->where(['invite_code' => $invite_code])->find();
            if (!$UserInfo) {
                $this->error(__('邀请人不存在'));
            }
            $extend['parent_user_id'] = $UserInfo['id'];
            $params['parent_user_id'] = (string)$UserInfo['id'];
            $extend['area'] = $area;
            $count = $userModel->where(['parent_user_id'=>$UserInfo['id']])->count();
            if(!$count){
                $area = "A";
                $extend['area'] = $area;
            }
            $parent_area_json = digui($params['parent_user_id'], $area);
            $extend['parent_area_json'] = $parent_area_json;
        }
        $ret = $this->auth->registertwo($username, $password, '', $mobile, $extend);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 短信验证码注册
     */
    public function smsRegister()
    {
        $user = auth_user();
        if ($user) {
            $this->error('您已登录,请先退出登录');
        }

        $params = $this->request->only(['mobile', 'code', 'password']);
        $this->svalidate($params, '.smsRegister');

        $ret = Sms::check($params['mobile'], $params['code'], 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        // 注册
        $userAuth = new UserAuth();
        $auth     = $userAuth->register($params);
        set_token_in_header($auth->getToken());

        $this->success(__('Sign up successful'));
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $user = auth_user();

        $params = $this->request->only(['oldPassword', 'newPassword']);
        $this->svalidate($params, '.changePassword');

        $userAuth = new UserAuth();
        $userAuth->changePassword($params['newPassword'], $params['oldPassword']);

        $this->auth->direct($user->id);
        set_token_in_header($this->auth->getToken());

        $this->success(__('Change password successful'));
    }

    /**
     * 安全密码
     * secure_password
     */
    public function changeSecurePassword()
    {
        $params = $this->request->only(['secure_password']);
        $this->svalidate($params, '.securePassword');

//        $ret = Ems::check($params['email'], $params['code'], 'secure_password');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
        $userAuth = new UserAuth();
        $params['user_id'] = $this->auth->id;
        $userAuth->resetSecurePassword($params);
        $this->success(__('修改成功'));
    }

    /**
     * 重置/忘记密码
     */
    public function resetPassword()
    {
        $params = $this->request->only(['email', 'password']);
        if(empty($params['email']) || empty($params['password']) ){
            $this->error(__('缺少参数'));
        }
//        $ret = Ems::check($params['email'], $params['code'], 'resetpwd');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }

        $userAuth = new UserAuth();
        $userAuth->resetPassword($params);

        $this->success(__('Reset password successful'));
    }

    /**
     * 更换手机号
     */
    public function changeMobile()
    {
        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.changeMobile');

        $ret = Sms::check($params['mobile'], $params['code'], 'changemobile');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->changeMobile($params);

        $this->success('绑定成功');
    }

    /**
     * 修改用户名
     */
    public function changeUsername()
    {
        $user = auth_user(true);

        $params = $this->request->only(['username']);
        $this->svalidate($params, '.changeUsername');

        $userAuth = new UserAuth();
        $userAuth->changeUsername($params);

        $this->success('绑定成功');
    }

    /**
     * 更新小程序头像和昵称
     */
    public function updateMpUserInfo()
    {
        $user = auth_user(true);

        $params = $this->request->only(['avatar', 'nickname']);
        $this->svalidate($params, '.updateMpUserInfo');

        $user->save($params);

        $thirdOauth = \app\admin\model\shopro\ThirdOauth::where('user_id', $user->id)->where([
            'provider' => 'wechat',
            'platform' => 'miniProgram'
        ])->find();
        $thirdOauth->save($params);
        $this->success('绑定成功');
    }


    /**
     * 登出
     */
    public function logout()
    {
        $userAuth = new UserAuth();
        $userAuth->logout();

        $this->success(__('Logout successful'));
    }


    /**
     * 用户注销
     */
    public function logoff()
    {
        $userAuth = new UserAuth();
        $userAuth->logoff();

        $this->success('注销成功');
    }

    /**
     * @menu 店铺申请
     * ''
     * @Date:2024-04-15 09:33
     */
    public function shop_apply()
    {
        $model     = new Shop();
        $shop_info = $model->where(['user_id' => $this->auth->id])->find();
        $params    = $this->request->only([
            'shop_name',
            'nation',
            'province_name',
            'city_name',
            'district_name',
            'mobile',
            'licence_image',
            'invite_code'
        ]);
        $this->svalidate($params, '.shopApply');
        $params['user_id'] = $this->auth->id;
        $params['address'] = $params['province_name'].'-'.$params['city_name'].'-'.$params['district_name'];
        if(!empty($params['invite_code'])){
            $userInfo = \app\common\model\User::where(['invite_code'=>$params['invite_code']])->find();
            if(!$userInfo){
                $this->error('邀请人不存在');
            }
            $params['parent_id'] = $userInfo['id'];
            unset($params['invite_code']);
        }
        if ($shop_info) {
            if ($shop_info['status'] == 0) {
                $this->error('店铺正在审核中，请勿重复提交');
            }
            if ($shop_info['status'] == 1) {
                $this->error('您已经是店铺，请勿重复申请');
            }
            $params['status'] = 0;
            $shop_info->save($params);
            $this->success('申请成功');
        }

        $model->create($params);
        $this->success('申请成功');
    }

    /**
     * @menu 店铺列表
     * ''
     * @Date:2024-04-15 10:35
     */
    public function shop_list()
    {
        $model = new Shop();
        $data  = $model->where(['status' => 1])->select();
        $this->success('ok', $data);
    }


    /**
     * @menu 商铺进货
     * ''
     * @Date:2024-04-21 11:13
     */
    public function shop_restock(){
        $model = new Shop();
        $shop_info = $model->where(['status'=>1,'user_id'=>$this->auth->id])->find();
        if(!$shop_info){
            $this->error('只有审核通过的商铺才能进货哦');
        }
        $params = $this->request->param();
        if(empty($params['goods_list'])){
            $this->error('参数错误');
        }
        $count = 0;
        Db::startTrans();
        try {
            $inser = [];
            $goodsModel = new Goods();
            foreach ($params['goods_list'] as $k=>$v){
                $goodsInfo = $goodsModel->where(['id'=>$v['goods_id'],'status'=>'up','type'=>'card'])->find();
                if(!$goodsInfo){
                    $this->error('商品ID-'.$v['goods_id'].'不存在或已经下架');
                }
                $inser[$k]['goods_num'] = $v['goods_num'];
                $inser[$k]['goods_id']  = $v['goods_id'];
                $inser[$k]['shop_id']   = $shop_info['id'];
                $inser[$k]['user_id']   = $this->auth->id;
                $inser[$k]['all_money'] = bcmul($goodsInfo['price'][0], $v['goods_num']);
                if(!empty($params['remark'])){
                    $inser[$k]['remark'] = $params['remark'];
                }
            }
            $shopRestockModel = new ShopRestockModel();
            $count = $shopRestockModel->saveAll($inser);
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error('操作失败');
    }

    /**
     * @menu 进货列表
     * ''
     * @Date:2024-04-21 14:54
     */

    public function shop_restock_list(){
        $model = new ShopRestockModel();
        $where['user_id'] = $this->auth->id;
        $status = input('status');
        if(isset($status) && $status != ''){
            $where['status'] = $status;
        }
        $query =  $model->with(['goods'=>function($query){
            $query->field('id,title,subtitle,image,price');
        }])->where($where);
        $date = $this->request->param('date/a');
        if($date){
            $query = $query->whereTime('createtime', 'between', $date);
        }
        $data  =$query->field('id,goods_id,goods_num,status')->paginate();
        $this->success('ok',$data);
    }


    public function shop_info(){
        $model = new Shop();
        $shop_info = $model->where(['status'=>1,'user_id'=>$this->auth->id])->find();
        $this->success('ok',$shop_info);
    }

    /**
     *国家
     */
    public function nation(){
        $arr = ['zh-CN'=>'中国','mongolia'=>'蒙古国','russian'=>'俄罗斯','korean'=>'韩国','japan'=>'日本','kazakhstan'=>'哈萨克斯坦'];
        $this->success('ok',$arr);
    }

    /**
     * 业绩
     */
    public function yeji(){
        $model = new ShoproPerformanceModel();
        $where['user_id'] = $this->auth->id;
        $data = $model->where(['user_id'=>$this->auth->id])->paginate();
        $performance['a_performan'] = $model->where(['user_id'=>$this->auth->id])->sum('a_money');
        $performance['b_performan'] = $model->where(['user_id'=>$this->auth->id])->sum('b_money');
        $this->success('ok',['performan'=>$performance,'data'=>$data]);
    }

    /**
     * @menu 购车指标
     * ''
     * @Date:2024-05-20 22:40
     */
    public function car_goods(){
        $model = new CarQueue();
        $data  = $model->with(['goods'=>function($query){
            $query->field('id,title,image');
        }])->where(['user_id'=>$this->auth->id])->field('id,goods_id,money,createtime,status')->select();
        $this->success('ok',$data);
    }
}
